package com.cy4;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author CY
 * @date 2022/10/13 20:45
 **/
class MyStack2 {
    Queue<Integer> q1;
    Queue<Integer> q2;

    public MyStack2() {
        q1 = new LinkedList<Integer>();
        q2 = new LinkedList<Integer>();
    }

    public void push(int x) {
        if (!empty()) {
            if (q1.isEmpty()) {
                q2.offer(x);
            } else {
                q1.offer(x);
            }
        } else {
            q1.offer(x);
        }
    }

    public int pop() {
        if (empty()) {
            return -1;
        }
        int size = q1.size() - 1;
        if (!q1.isEmpty()) {
            for (int i = 0; i < size; i++) {
                q2.offer(q1.poll());
            }
            return q1.poll();

        } else {
            int size2 = q2.size() - 1;
            for (int i = 0; i < size2; i++) {
                q1.offer(q2.poll());
            }
            return q2.poll();
        }
    }

    public int top() {
        if (empty()) {
            return -1;
        }
        int size = q1.size() - 1;
        if (!q1.isEmpty()) {
            for (int i = 0; i < size; i++) {
                q2.offer(q1.poll());
            }
            int tmp = q1.poll();
            q2.offer(tmp);
            return tmp;

        } else {
            int size2 = q2.size() - 1;
            for (int i = 0; i < size2; i++) {
                q1.offer(q2.poll());
            }
            int tmp = q2.poll();
            q1.offer(tmp);
            return tmp;
        }

    }

    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();
    }

    public static void main(String[] args) {
        MyStack2 myStack2 = new MyStack2();

        myStack2.push(1);
        myStack2.push(2);
        myStack2.push(3);
        System.out.println(myStack2.top());
        myStack2.push(4);
        myStack2.push(9);
        System.out.println(myStack2.pop());
        System.out.println(myStack2.top());


//        System.out.println(myStack2.pop());
//        System.out.println(myStack2.empty());

    }
}
